package com.atguigu.lease.web.app.service.impl;


import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.atguigu.lease.common.constant.RedisConstant;
import com.atguigu.lease.common.exception.LeaseException;
import com.atguigu.lease.common.result.ResultCodeEnum;
import com.atguigu.lease.common.utils.JwtUtil;
import com.atguigu.lease.model.entity.SystemUser;
import com.atguigu.lease.model.entity.UserInfo;
import com.atguigu.lease.model.enums.BaseStatus;
import com.atguigu.lease.web.app.service.LoginService;
import com.atguigu.lease.web.app.service.UserInfoService;
import com.atguigu.lease.web.app.vo.user.LoginVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import javax.print.attribute.standard.OrientationRequested;
import java.util.Random;
import java.util.concurrent.TimeUnit;

@Service
public class LoginServiceImpl implements LoginService {
@Autowired
private UserInfoService userInfoService;
@Autowired
    private Client client;
@Autowired
private RedisTemplate<String,Object> redisTemplate;
    @Override
    public void getCode(String phone) throws Exception {
       //1.先行判断redis的key里是否有code,有的话代表验证码还没过期,并返回频繁获取异常
        String key = RedisConstant.APP_LOGIN_PREFIX+phone;
        Boolean a = redisTemplate.hasKey(key);
        if (a){
            throw new LeaseException(ResultCodeEnum.APP_SEND_SMS_TOO_OFTEN);
        }
        //2.发送验证码
        String code = "";
        Random random =new Random();
        for (int i = 0; i < 6; i++) {
            code+=random.nextInt(10);

        }
        SendSmsRequest sendSmsRequest = new SendSmsRequest();
        sendSmsRequest.setPhoneNumbers(phone);
        sendSmsRequest.setSignName("阿里云短信测试");
        sendSmsRequest.setTemplateCode("SMS_154950909");
        sendSmsRequest.setTemplateParam("{\"code\":\"" +code +"\"}\n");
        client.sendSms(sendSmsRequest);

        //3.把key(phone)和code(验证码)保存在redis里
        redisTemplate.opsForValue().set(key,code,RedisConstant.APP_LOGIN_CODE_TTL_SEC,TimeUnit.SECONDS);

    }

    @Override
    public String login(LoginVo loginVo) {
        //1.判断前端传过来的phone和code是否为空
        if (ObjectUtils.isEmpty(loginVo.getPhone())){
            throw new LeaseException(ResultCodeEnum.APP_LOGIN_PHONE_EMPTY);
        }

        if (ObjectUtils.isEmpty(loginVo.getCode())){
            throw new LeaseException(ResultCodeEnum.APP_LOGIN_CODE_EMPTY);
        }

        //2.判断redis里的code是否为null,如果为null,就代表验证码已过期
        String key = RedisConstant.APP_LOGIN_PREFIX+loginVo.getPhone();
        if (!redisTemplate.hasKey(key)){
            throw new LeaseException(ResultCodeEnum.APP_LOGIN_CODE_EXPIRED);
        }

        //3.判断前端传过来的code和redis里的code是否相等
        if (!redisTemplate.opsForValue().get(key).equals(loginVo.getCode())){
            throw new LeaseException(ResultCodeEnum.APP_LOGIN_CODE_ERROR);
        }

        //4.判断数据库中是否有phone(用户名)对应的用户,如果没有就新增用户
        LambdaQueryWrapper<UserInfo> a = new LambdaQueryWrapper<>();
        a.eq(UserInfo::getPhone,loginVo.getPhone());
        UserInfo userInfo = userInfoService.getOne(a);
        if (userInfo==null){
            UserInfo userInfo1 = new UserInfo();
            userInfo1.setPhone(loginVo.getPhone());
            userInfo1.setNickname("奥特曼");
            userInfo1.setStatus(BaseStatus.ENABLE);
            userInfo = userInfo1;
            userInfoService.save(userInfo1);

        }
        //5.判断用户状态是否禁用
        if (userInfo.getStatus()==BaseStatus.DISABLE){
            throw new LeaseException(ResultCodeEnum.APP_ACCOUNT_DISABLED_ERROR);
        }

        //6.返回给前端一个token
        return JwtUtil.createToken(userInfo.getId());

    }
}
